package com.sojson.config.filter;

import java.io.IOException;
import java.util.HashSet;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sojson.base.BaseFilter;
import com.sojson.util.StringUtil;

/**
 * WebSocket过滤器
 * 
 * @author liu
 * @date 2020-10-09
 */
public class WebSocketFilter implements BaseFilter {

    /** 不过滤的路径 */
    private HashSet<String> excludePath;
    /** Sec-WebSocket-Protocol */
    private final String SEC_WEBSOCKET_PROTOCOL = "Sec-WebSocket-Protocol";
    /** 参数名 */
    private final String PARAM_NAME = SEC_WEBSOCKET_PROTOCOL;

    /**
     * 获取WebSocket的参数并验证
     * 
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        chain.doFilter(request, response);

        // WebSocket只能通过Sec-WebSocket-Protocol来传递数据
        String header = ((HttpServletRequest)request).getHeader(PARAM_NAME);
        if (isNotBlankObject(header)) {
            // Sec-WebSocket-Protocol传过来的什么就必须返回什么,否则报错,如果传过来的是数组,就返回其中的任何一个
            ((HttpServletResponse)response).addHeader(PARAM_NAME, header.split(",")[0]);
        }
    }

    /**
     * 判断一个对象是否不是空(空对象)
     * 
     * @param obj
     * @return
     */
    private boolean isNotBlankObject(Object obj) {
        return StringUtil.isNotBlankObject(obj);
    }

    /**
     * 获取不过滤的路径
     * 
     * @return
     */
    @Override
    public HashSet<String> getExcludePath() {
        return this.excludePath;
    }

    /**
     * 设置不过滤的路径
     * 
     * @param excludePath
     */
    @Override
    public void setExcludePath(HashSet<String> excludePath) {
        this.excludePath = excludePath;
    }

    /**
     * 获取当前过滤器的名字
     */
    @Override
    public String getName() {
        String name = "skt";
        return name;
    }

}